package cn.kbkwwk.os.global;

import javafx.application.Platform;
import javafx.scene.control.TextArea;

/**
 * ClassName: Mutex
 * Package: cn.kbkwwk.os.global
 * Description:
 *
 * @Date: 2022-06-06 0:31 星期一
 * @Author: Kevin
 */
public class Mutex {
    private Integer mutex;

    public Mutex(Integer mutex) {
        this.mutex = mutex;
    }

    public Integer getMutex() {
        return mutex;
    }

    public void setMutex(Integer mutex) {
        this.mutex = mutex;
    }

    public void addText(String str) {
        TextArea textArea = GlobalData.myController.getMyText();
        Platform.runLater(() -> {
            textArea.appendText(str);
        });
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized void pMutex() {
        if (mutex == 0) {//等待其他人就餐完毕
            try {
                int threadIndex = Integer.parseInt(Thread.currentThread().getName().substring(7)) - 4;
                String text = "Thread-" + threadIndex + " waiting for dining!!!!" + "\n";
                System.out.print(text);
                addText(text);
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        mutex--;
    }

    public synchronized void vMutex() {
        mutex++;
        notifyAll();
        int threadIndex = Integer.parseInt(Thread.currentThread().getName().substring(7)) - 4;
        String text = "Thread-" + threadIndex + " end of dining!!!!" + "\n";
        System.out.print(text);
        addText(text);
    }
}
